package com.gcloud.core.currentUser.policy.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import com.gcloud.core.currentUser.policy.enums.ResourceIsolationType;
import com.gcloud.core.currentUser.policy.model.FilterPolicyModel;
import com.gcloud.header.api.model.CurrentUser;
import com.gcloud.header.common.ResourceOwner;

import lombok.extern.slf4j.Slf4j;
/**
Copyright (c) [2020] [G-CLOUD TECHNOLOGY] [G-Cloud 8.0] is licensed under the Mulan PSL v1.
You can use this software according to the terms and conditions of the Mulan PSL v1. You may obtain
a copy of Mulan PSL v1 at: http://license.coscl.org.cn/MulanPSL THIS SOFTWARE IS PROVIDED ON AN 
"AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v1 for more details.
 */

@Component
@Slf4j
public class AllTenantIsolationCheck implements IIsolationTypeCheck {
	
	@PostConstruct
    private void init() {

    }

	@Override
	public ResourceIsolationType resourceIsolationType() {
		return ResourceIsolationType.ALL_TENANT;
	}

	@Override
	public void check(ResourceOwner resourceOwner, CurrentUser currentUser) {
		return;
	}

	@Override
	public FilterPolicyModel resourceFilter(CurrentUser currentUser, String prefix) {
		FilterPolicyModel model = new FilterPolicyModel();
		List<Object> params = new ArrayList<Object>();
		StringBuffer sqlWhereBuff = new StringBuffer();
		sqlWhereBuff.append(" ");
		if(!StringUtils.isBlank(currentUser.getDefaultTenant())) {
		    sqlWhereBuff.append(" AND ");
			sqlWhereBuff.append( prefix + "tenant_id = ? ");
			params.add(currentUser.getDefaultTenant());
		}
		
		model.setParams(params);
		model.setWhereSql(sqlWhereBuff.toString());
		
		return model;
	}

}